package com.itheima.demo;

import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;


import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DemoTest1 {
    // 将需要的变量定义为全局变量 (成员变量 )
    private SqlSession session = null;
    private InputStream is = null;

    // 抽取简化
    @Before //@Before是在 @Test之前执行的方法
    public void before() throws IOException {
// 读取核心配置文件 获得输入流 赋值给is
        is = Resources.getResourceAsStream("sql.xml");
        // 通过构建者构建SqlSessionFactory 对象
//        SqlSessionFactory factory=new
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //通过factory获取SqlSession对象
      session = factory.openSession();

    }

    @After //在@Test之后执行
    public void after() throws Exception{
        //5、事务提交
        session.commit();
        //6、释放资源
        session.close();
        is.close();
    }

    @Test
    public void findSex() {
//        获取 返回对象
        List<Map> map = session.selectList("one.findSex");
//   map1 { sex= 男  count =？}
//   map2{sex=女  count=？}    合并为一个集合  男=cont？  女=cont
        Map sexMap = new HashMap();
        for (Map map1 : map) {
            String sex = (String) map1.get("sex");
            long total = (long) map1.get("count(*)");
            sexMap.put(sex, total);
        }
        System.out.println(sexMap);
    }
    //修改测试
    @Test
    public void testUpdateById(){
        User user = session.selectOne("one.findById", 12);
        user.setUsername("貂蝉");
        session.update("one.updateById",user);
    }

    @Test
    public void testFindByEmailAndPwd(){
        //封装数据
        Map map=new HashMap();
        map.put("em","111@qq.com");
        map.put("pd","147");
        User user = session.selectOne("one.findByEmailAndPwd",map);
        System.out.println(user);
    }
    @Test
    public  void testFindLikeName() {
        //模糊查询测试
        //  传参
        List<User> list = session.selectList("one.findLikeName", "%吕%");
        // 字符串拼接s
//        List<Object> list = session.selectList("one.findLikeName", "吕");
        System.out.println(list);
    }
    //新增操作
    @Test
    public  void testSave(){

        User user = new User();
        user.setUsername("老妹");
        user.setSex("女");
        user.setAge(31);
        user.setPassword("123456");
        user.setEmail("666@qq.com");
        System.out.println("执行保存前："+user);
        session.insert("one.saveUser",user);
        System.out.println("执行保存后："+user);
    }
}
